package top.huntwolf.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.huntwolf.admin.common.JsonResult;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.service.BannerService;
import top.huntwolf.admin.utils.QiniuCloudUtil;
import top.huntwolf.admin.utils.UUIDUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;


@CrossOrigin
@RestController
@RequestMapping("/banner")
@Api(description = "banner轮播图")
public class BannerController {

    @Autowired
    BannerService bannerService;

    @GetMapping("")
    @ApiOperation("获取所有banner表信息")
    public JsonResult searchAll(){
        return JsonResult.success(bannerService.searchAllBanner());
    }

    // 删
    @DeleteMapping("/{id}")
    @ApiOperation("删除对应id的信息")
    public JsonResult deleteBanner(@PathVariable Integer id) {
        bannerService.deleteBanner(id);
        return JsonResult.success(null);
    }


    //上传图片 涉及数据库操作 插入banner表 url
    @PostMapping("uploadImg")
    @ApiOperation("上传图片")
    public JsonResult uploadImg(@RequestParam MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()){
            return JsonResult.error(CodeMsg.BIND_ERROR.fillArgs("文件为空，请重新上传"));
        }
        //springboot内嵌的tomcat 参数设置 上传的文件最大 1M

        try {
            System.out.println(file.getSize());
            byte[] bytes = file.getBytes();


            String imageName = UUIDUtil.getUUID();
            try {
                //使用base64方式上传到七牛云
                String url = QiniuCloudUtil.put64image(bytes,imageName);

                //插入数据库
                bannerService.insertBanner(url);

                return JsonResult.success(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResult.error(CodeMsg.SERVER_ERROR.fillArgs("文件上传异常"));

    }
}
